class TreeNode(object):
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right


class Solution(object):
    def maxAncestorDiff(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        self.v = -float('inf')

        def search(node):
            if not node.left and not node.right:
                return node.val, node.val
            next_min = float('inf')
            next_max = -float('inf')
            if node.left:
                n1, n2 = search(node.left)
                next_min = min(next_min, n1)
                next_max = max(next_max, n2)
            if node.right:
                n1, n2 = search(node.right)
                next_min = min(next_min, n1)
                next_max = max(next_max, n2)
            self.v = max(self.v, abs(node.val - next_min), abs(node.val - next_max))
            return min(node.val, next_min), max(node.val, next_max)

        search(root)
        return self.v